//
//  MixingView.m
//  CocoaSynth
//
//  Created by Thomas Dupont on 18/02/10.
//  Copyright 2010 Apple Inc. All rights reserved.
//

#import "MixingView.h"

#import "BankVCOView.h"
#import "ModuleViewController.h"
#import "Module.h"
#import "Factory.h"
#import "BankModuleViewControllerProtocol.h"
#import "MixingViewController.h"

#define myPrivateType @"myPrivateType"

int bringToFront(id itemA, id itemB, void *target);

@implementation MixingView

@synthesize controller;

- (id)initWithFrame:(NSRect)frameRect
{
	if (self = [super initWithFrame:frameRect]) {
		[self registerForDraggedTypes:[NSArray arrayWithObject:myPrivateType]];
	}
	return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
	[[NSColor clearColor] set];
	[NSBezierPath fillRect:dirtyRect];
}

- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender
{
	return NSDragOperationCopy;
}

- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender
{
	NSPasteboard* pb = [sender draggingPasteboard];
	NSData* data = [pb dataForType:myPrivateType];
	if (data == nil) {
		return NO;
	}
	id<BankModuleViewControllerProtocol> bankController = [NSKeyedUnarchiver unarchiveObjectWithData:data];
	
	ModuleViewController* moduleController = [bankController createModule];
	
	NSView* view = [moduleController view];
	
	NSPoint imagePoint = [sender draggedImageLocation];
	imagePoint = [self convertPoint:imagePoint fromView:nil];
	
	[view setFrameOrigin:imagePoint];
	
	[controller addModule:moduleController];
	
	return YES;
}

- (void)mouseDown:(NSEvent *)theEvent
{
	[controller removeParameterView];
	[controller unselectPorts];
}

- (void)bringSubviewToFront:(NSView *)subview
{
    [self sortSubviewsUsingFunction:(NSComparisonResult (*)(id, id, void *))bringToFront context:subview];
}

int bringToFront(id itemA, id itemB, void *target)
{
    if (itemA == target) {
        return NSOrderedDescending;
    } else {
        return NSOrderedSame;
    }
}


@end
